package net.yxsoft.kit;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.ehcache.CacheKit;
import net.yxsoft.resource.CacheRes;
import rapid.util.StrKit;

import java.util.HashMap;
import java.util.Map;

public class BackendTokenKit {
    public static String  getBackendToken(){
        String frontToken= CacheKit.get(CacheRes.CACHE_BACKENDTOKEN,CacheRes.CACHE_BACKENDTOKEN);
        if(StrKit.isBlank(frontToken)) {

            String timestamp = Long.toString(System.currentTimeMillis() / 1000);
            String nonceStr = NonceStr.createNonceStr();
            String secret = PropKit.get("ysf.secret");
            String appid = PropKit.get("ysf.appId");
            String backendTokenurl=PropKit.get("ysf.backendTokenurl");
            String signaturestr = "appId=" + appid + "&nonceStr=" + nonceStr + "&secret=" + secret + "&timestamp=" + timestamp;
            byte[] signaturebyte = signaturestr.getBytes();
            String signature = Sha256Kit.sha256(signaturebyte);
            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("appId", appid);
            paramMap.put("nonceStr", nonceStr);
            paramMap.put("timestamp", timestamp);
            paramMap.put("signature", signature);
            //String jsonStr = HttpKit.post("https://open.95516.com/open/access/1.0/backendToken?appId="+appid+"&nonceStr="+ nonceStr+"&timestamp="+timestamp+"&signature="+signature+"","");
            String jsonStr = HttpKit.post(backendTokenurl, JsonKit.toJson(paramMap));

            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            if(jsonObject.getString("resp").equals("00")) {
                JSONObject jsonObjectparames = JSONObject.parseObject(jsonObject.getString("params"));


                CacheKit.put(CacheRes.CACHE_BACKENDTOKEN, CacheRes.CACHE_BACKENDTOKEN, jsonObjectparames.getString("backendToken"));

            return jsonObjectparames.getString("backendToken");
            }else{
                return jsonObject.getString("resp")+":"+jsonObject.getString("msg");
            }
        }else {
            return frontToken;
        }
    }
}
